#include "udp_server.hpp"
#include <memory>
#include <string>

using namespace ns_server;
using namespace std;

static void usage(std::string proc)
{
    std::cout << "Usage:\n\t" << proc << " prot\n" << std::endl;
}

std::string transaction(std::string request)
{
    std::string result;
    char c;
    for (auto &r : request)
    {
        if (islower(r))
        {
            c = toupper(r);
            result.push_back(c);
        }
        else
        {
            result.push_back(r);
        }
    }
    return result;
}

static bool isPass(const std::string &command)
{
    bool pass = true;
    auto pos = command.find("rm");
    if (pos != std::string::npos)
    {
        pass = false;
    }
    pos = command.find("mv");
    if (pos != std::string::npos)
    {
        pass = false;
    }
    pos = command.find("while");
    if (pos != std::string::npos)
    {
        pass = false;
    }
    pos = command.find("kill");
    if (pos != std::string::npos)
    {
        pass = false;
    }
    return pass;
}

std::string executeCommand(std::string command)
{
    //安全检查
    if (!isPass(command))
    {
        return "you are so bad!";
    }
    //业务逻辑处理
    FILE* fp = popen(command.c_str(), "r");
    if (fp == nullptr)
    {
        return "None";
    }

    char line[2048];
    std::string result;
    while (fgets(line, sizeof(line), fp) != nullptr)
    {
        result += line;
    }
    pclose(fp);

    return result;
}

//  ./udp_server port
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t port = atoi(argv[1]);

    //unique_ptr<UdpServer> usvr(new UdpServer("1.1.1.1", 8081));
    // unique_ptr<UdpServer> usvr(new UdpServer(transaction, port));
    // unique_ptr<UdpServer> usvr(new UdpServer(executeCommand, port));
    unique_ptr<UdpServer> usvr(new UdpServer(port));

    //usvr->InitServer();
    usvr->start();
    return 0;
}